package com.googlecode.ilstreets;

import java.io.ByteArrayOutputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Get;

import javax.jdo.Query;
import com.googlecode.ilstreets.persistent.City;

public class CityResource extends ParameterizedServerResource {

    @SuppressWarnings("unchecked")
	@Get("json")
    public Object doGet() {
    	if (!params.containsKey("base"))
    	{
    		return Collections.EMPTY_LIST;
    	}
    	
    	String base = params.get("base");
    	if (base.length() == 0)
    	{
    		return Collections.EMPTY_LIST;
    	}

        PersistenceManager pm = PMF.get().getPersistenceManager();
        
        Query query = pm.newQuery(City.class);
        query.setOrdering("name");
        List<City> cities = Collections.EMPTY_LIST;
        try
        {
			cities = (List<City>)query.execute();
        } finally
        {
        	query.closeAll();
        }
        List<String> result = new LinkedList<String>();
        for (City city : cities)
        {
        	if (city.getName().startsWith(base))
        	{
        		result.add(city.getName());
        	}
        }
        
        if (params.containsKey("callback"))
        {
        	String resultStr = "undefined";
        	
        	try
        	{
	        	ByteArrayOutputStream baos = new ByteArrayOutputStream();
        		ObjectMapper mapper = new ObjectMapper();
        		mapper.writeValue(baos, result);
	        	resultStr = baos.toString("UTF8");
        	} catch (Exception e) {
			}
        	
        	return params.get("callback")+"("+resultStr+");";
        }
        else
        {
        	return result;
        }
    }
}